package com.hyq.learn.web.util;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;

/**
 * @author : chenzetao
 * @since : 2020/7/29
 */
public class ServletRequestUtil {

    /**
     * 获取请求的IP地址
     *
     * @param request HttpServletRequest
     * @return IP地址
     */
    public static String ipAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip)) {
            ip = ip.split(",")[0];
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String ipAddress() {
        return ipAddress(getCurrentRequest());
    }

    /**
     * 判断请求是不是来自内网
     *
     * @param request HttpServletRequest
     * @return true-请求来自内网
     */
    public static boolean isIntranet(HttpServletRequest request) {
        final InetAddress ip;
        try {
            ip = InetAddress.getByName(ServletRequestUtil.ipAddress(request));
        } catch (Exception e) {
            return false;
        }
        return ip.isLoopbackAddress() || ip.isSiteLocalAddress();
    }

    public static boolean isIntranet() {
        return isIntranet(getCurrentRequest());
    }

    /**
     * 解析请求的完整请求路径
     *
     * @param request HttpServletRequest
     * @return URL+queryS 完整请求路径
     */
    public static String parsePath(HttpServletRequest request) {
        String url = request.getRequestURI();
        if (StringUtils.isNotBlank(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        return url;
    }

    public static String parsePath() {
        return parsePath(getCurrentRequest());
    }

    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

}
